<template>
  <div>
      <page-view :avatar="user.avatar" :title="false">

        <div slot="headerContent">
            <div class="title">{{ timeFix }}，{{ this.$store.getters.name==""?this.$store.getters.info.username:this.$store.getters.name}}
                <span class="welcome-text">，{{ welcome }}</span></div>
        </div>
        <div slot="extra">
            <a-row class="more-info">
                <a-col :span="8">
                    <head-info title="应用" content="56" :center="false" :bordered="false"/>
                </a-col>
                <a-col :span="8">
                    <head-info title="设备" :content="(clientData.length).toString()" :center="false" :bordered="false"/>
                </a-col>
                <a-col :span="8">
                    <head-info title="消息数" :content="count['msg']" :center="false" />
                </a-col>
            </a-row>
        </div>
          <div style="height: 80px">
              <a-row :gutter="24">
                  <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
                      <chart-card :loading="loading" title="总信息量" :total="count['all']">
                          <a-tooltip title="指标说明" slot="action">
                              <a-icon type="info-circle-o" />
                          </a-tooltip>
                          <div>
                              <div class="up" style="margin-right: 16px;">
                                  <span slot="term">运行状态：</span>
                                  <a-progress :percent="50" size="small" status="active" />

                              </div>
                          </div>
                      </chart-card>

                  </a-col>
                  <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
                      <chart-card :loading="loading" title="MQTT内存占用" :total="this.$store.getters.node.memory_used==null ? node.memory_used :this.$store.getters.node.memory_used">
                          <a-tooltip title="指标说明" slot="action">
                              <a-icon type="info-circle-o" />
                          </a-tooltip>
                          <div style="height: 40px">
                              <span style="line-height: 20px">内存占有率</span>
                              <a-progress strokeLinecap="square" :percent="memprcent" style="line-height: 20px;"/>
                          </div>

                      </chart-card>
                  </a-col>
                  <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
                      <chart-card :loading="loading" title="CPU" :total=" this.$store.getters.node.memory_total==null ? node.memory_total:this.$store.getters.node.memory_total">
                          <a-tooltip title="指标说明" slot="action">
                              <a-icon type="info-circle-o" />
                          </a-tooltip>
                          <div style="width: 100%;height: 40px;">
                              <p style="line-height: 12px; margin-top: 10px;position:absolute;">最近1/5/15分钟平均负载:</p>
                              <p style="line-height: 12px; margin-top: 32px;position:absolute;color: #0ba360">
                                  {{this.$store.getters.node.load1==null ? node.load1+'/'+node.load5+'/'+node.load15:this.$store.getters.node.load1+'/' + this.$store.getters.node.load5+'/'+ this.$store.getters.node.load15}}
                              </p>
                          </div>

                      </chart-card>
                  </a-col>
                  <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
                      <chart-card :loading="loading" title="运行状况" :total="node.process_used  +'/'+ node.process_available">
                          <a-tooltip title="指标说明" slot="action">
                              <a-icon type="info-circle-o" />
                          </a-tooltip>
                          <div style="width: 100%;height: 40px;">
                              <p style="line-height: 12px; margin-top: 10px;position:absolute;">平台当前连接设备总数：</p>
                              <p style="line-height: 12px; margin-top: 32px;position:absolute;color: #0ba360">{{this.$store.getters.node.connections==null?node.connections:this.$store.getters.node.connections}}</p>
                          </div>

                      </chart-card>
                  </a-col>
              </a-row>
          </div>
        <div>
            <a-row :gutter="24">
                <a-col :xl="16" :lg="24" :md="24" :sm="24" :xs="24">
                    <a-card class="project-list" :loading="loading" style="margin-bottom: 24px;margin-top: 0px" :bordered="false"
                            title="设备列表" :body-style="{ padding: 0 }">

                        <a-table :columns="columns" :dataSource="clientData" v-show="clientData.length==0? false:true"
                        style="padding: 10px">
                            <a slot="name" slot-scope="text">{{text}}</a>
                            <span slot="customTitle">id</span>
                            <span slot="state" slot-scope="state">
                                  <div style="width: 80px;height: 20px;margin-top: 0px">
                                        <div :class="[state==1 ?'online':'offline']" style="float: left;margin-top: 2px"></div>
                                        <span style="float: left;margin-left: 10px">{{state==1?'在线':'离线'}}</span>
                                  </div>
                            </span>
                            <span  slot="topic" slot-scope="topic,record">
                                <a-popconfirm placement="top" okText="关闭" cancelText="取消" >
                                <template slot="title">
                                    <p>订阅个数：{{topic.length}}</p>
                                    <p>主题</p>
                                    <div style="width: 140px;" >
                                     <a-tag v-for="tag in topic" :color="tag==='loser' ? 'volcano' : (tag.length > 5 ? 'geekblue' : 'green')"
                                       :key="tag" style="float:left;margin: 2px">
                                       {{tag==null?tag='无':tag.toUpperCase()}}
                                      </a-tag>
                                   </div>

                                </template>
                                <a-button @click="getSubscribe(record.clientid,record.key)" :disabled="record.state==0?true:false">查看</a-button>
                              </a-popconfirm>


                            </span>

                        </a-table>
                        <div style="min-height: 320px">
                            <a-empty v-show="clientData.length==0? true: false" style="margin-top: 100px"
                                     image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                                <span slot="description"> 暂无数据 </span>
                            </a-empty>
                        </div>
                    </a-card>
                </a-col>
                <a-col style="padding: 0 12px" :xl="8" :lg="24" :md="24" :sm="24" :xs="24">
                    <a-card title="操作日志" style="margin-bottom: 24px;" :bordered="false" :body-style="{padding: 0}">

                        <div style="padding: 10px;max-height: 480px;min-height:460px;">
                            <a-tabs  type="card" >
                                <a-tab-pane tab="订阅" key="1"  style="overflow:scroll;max-height:480px">
                                    <a-list itemLayout="horizontal" :dataSource="sublogdata" style="padding: 10px;max-height: 360px;margin-bottom:40px">
                                        <a-list-item slot="renderItem" slot-scope="item">
                                            <div style="width: 50px;height: 50px">
                                                <a-avatar style="backgroundColor:#87d068">{{item.event}}</a-avatar>
                                            </div>
                                            <div style="width:100%;margin-left: 5px">
                                                <p>{{ "设备"+item.clientid+'在'+moment(item.time).format("YYYY-MM-DD HH:mm:ss")+item.event+'主题：'}}<a-tag color="#108ee9">{{item.topic}}</a-tag></p>
                                            </div>
                                        </a-list-item>
                                    </a-list>

                                </a-tab-pane>
                                <a-tab-pane tab="连接" key="2">

                                    <a-list itemLayout="horizontal" :dataSource="conlogdata" style="padding: 10px;max-height: 360px;margin-bottom:40px">
                                        <a-list-item slot="renderItem" slot-scope="item">
                                            <div style="width: 50px;height: 50px">
                                                <a-avatar style="backgroundColor:#87d068">{{item.event}}</a-avatar>
                                            </div>
                                            <div style="width:100%;margin-left: 5px">
                                                <p>{{ "设备"+item.clientid+'在'+moment(item.time).format("YYYY-MM-DD HH:mm:ss")+
                                                    item.event}}
                                                </p>
                                            </div>
                                        </a-list-item>
                                    </a-list>


                                </a-tab-pane>
                            </a-tabs>

                        </div>

                    </a-card>

                </a-col>
            </a-row>
        </div>
      </page-view>
  </div>
</template>

<script>

    import {timeFix} from "@/components/tools/util";
    import HeadInfo from '@/components/tools/HeadInfo'
    import PageView from "@/components/layout/PageView";
    import ChartCard from "@/components/charts/ChartCard";
    //import MiniProgress from "@/components/charts/MiniProgress";
    import { mapActions,mapGetters } from 'vuex'
    import {getClient, getNode,getSubscriptions,getSubLog,getClientLog,getcount} from '@/api/mqtt'
    import moment from 'moment';


    //

    const columns = [
        {
            dataIndex: 'clientid',
            key: 'clientid',
            slots: { title: 'customTitle' },
            scopedSlots: { customRender: 'id' },
        },
        {
            title: '设备名称',
            dataIndex: 'clientname',
            key: 'clientname',
        },
        {
            title: '状态',
            key: 'state',
            dataIndex: 'state',
            slots: { title: 'state' },
            scopedSlots: { customRender: 'state' },
        },
        {
            title: '订阅',
            key: 'topic',
            dataIndex: 'topic',
            slots: { title: 'topic' },
            scopedSlots: { customRender: 'topic' },
        },

    ];
    const clientData = [];


    export default {
        name: "Workplace",
        components: {
            ChartCard,
            //MiniArea,
            //MiniProgress,
            HeadInfo,
            PageView
        },


        data(){
            return {
                conlogdata:[],
                columns,
                clientData,
                memprcent:20,
                clientStatus:true,
                startDate:new Date().getFullYear()+'/'+new Date().getMonth()+'/'+new Date().getDate(),
                endDate:new Date().getFullYear()+'/'+new Date().getMonth()+'/'+new Date().getDate(),
                dateFormat: 'YYYY/MM/DD',
                sublogdata:[],
                node:[],
                timeFix: timeFix(),
                user:{
                    "name":"",
                    "avatar":"",
                  },
                welcome:'祝你开心每一天！',
                loading: false,
                radarLoading: true,
                count:[],

            }
        },
        beforeCreate(){



        },

        computed: {
            ...mapActions(['GetInfo','GetNode',]),
            ...mapGetters(['info']),

        },
        created() {
            this.getInfo();
            this.getClients();
            this.getSubscriptionsLog();
            this.getClientsLog()
            getNode().then((res)=>{
                //console.log(res.data.data[0])
                this.node=res.data.data[0]
            }).catch()
            this.getcount()
            //this.mem=parseInt(this.$store.getters.node.memory_used)/parseInt(this.$store.getters.node.memory_total)*100
            //.log(typeof(this.$store.getters.node.memory_used))//(0, this.$store.getters.node.memory_used.length - 1)))
        },
        beforeMount(){

        },
        mounted () {
            //this.Getinfo();
            //console.log(this.date1)
        },
        methods: {
            moment,
            getcount(){
                getcount().then((response)=>{
                    const result=response.data
                    //console.log(result)
                    this.count["all"]=result["all"].toString()
                    this.count["msg"]=result["username"].toString()
                }).catch()

            },

            getSubscriptionsLog(){
                //// console.log(e)
                getSubLog().then((reponse)=>{
                    const result =reponse.data.results
                    //console.log(result)
                    eval(result).forEach((item)=>{
                        this.sublogdata.push({event:item.event,time:item.add_time,
                            topic:item.topic,clientid:item.clientid})
                    })
                    //console.log(this.sublogdata)

                }).catch((error)=>{
                    console.log(error)
                })
            },

            getClientsLog(){

                getClientLog().then((reponse)=>{
                    const result =reponse.data.results
                   // console.log(result)
                    eval(result).forEach((item)=>{

                        this.conlogdata.push({event:item.event,time:item.add_time,
                            node:item.node,clientid:item.clientid})

                    })
                }).catch((error)=>{
                    console.log(error)
                })
            },
            getSubscribe(e,index){
               //// console.log(e)
                getSubscriptions(e).then((reponse)=>{
                    const result =reponse.data.data
                    //console.log(result)
                    eval(result).forEach((item)=>{
                        //console.log(index+'123')
                        //console.log(item.topic)
                        this.clientData[index]["topic"].push(item.topic)

                    })
                    }).catch((error)=>{
                    console.log(error)
                    })
            },
            onChange(dates, dateStrings) {
                console.log('From: ', dates[0], ', to: ', dates[1]);
                console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
            },
            ToFiles(){
                this.$router.push({name:'Files'}).catch(err => {err})
            },
            ToWorkplace(){
                this.$router.replace({name:'Workplace'}).catch(err => {err})
            },
            ToDev(){
                this.$router.replace({name:'Add'}).catch(err => {err})
            },
            ToApp(){
                this.$router.replace({name:'AppManger'}).catch(err => {err})
            },
            ToDebugg(){
                this.$router.replace({name:'Debug'}).catch(err => {err})
            },
            getClients(){

                getClient().then((res)=>{
                    //console.log(res.data)
                    sessionStorage.setItem('client',JSON.stringify(res.data))
                    this.clientData=res.data
                }).catch()
            },

            getInfo() {
                const {GetInfo}=this;
                GetInfo.then((reponse) => {
                    const result =reponse.data.results[0]
                    //console.log(result)
                    this.user.avatar=result.avater

                }).catch(() => {
                        this.$router.push({ "name": "login"})
                })
            },



        }
    }
</script>
<style scoped>
 .online{
     width: 16px;
     height: 16px;
     border-radius: 50%;
     background-color: #0ba360;
 }
  .offline{
      width: 16px;
     height: 16px;
      border-radius: 50%;
      background-color: #999999;
  }
</style>

<style lang="less" scoped>
        .project-list {

    .card-title {
        font-size: 0;

    a {
        color: rgba(0, 0, 0, 0.85);
        margin-left: 12px;
        line-height: 24px;
        height: 24px;
        display: inline-block;
        vertical-align: top;
        font-size: 14px;

    &:hover {
         color: #1890ff;
     }
    }
    }
    .card-description {
        color: rgba(0, 0, 0, 0.45);
        height: 44px;
        line-height: 22px;
        overflow: hidden;
    }
    .project-item {
        display: flex;
        margin-top: 8px;
        overflow: hidden;
        font-size: 12px;
        height: 20px;
        line-height: 20px;
    a {
        color: rgba(0, 0, 0, 0.45);
        display: inline-block;
        flex: 1 1 0;

    &:hover {
         color: #1890ff;
     }
    }
    .datetime {
        color: rgba(0, 0, 0, 0.25);
        flex: 0 0 auto;
        float: right;
    }
    }
    .ant-card-meta-description {
        color: rgba(0, 0, 0, 0.45);
        height: 44px;
        line-height: 22px;
        overflow: hidden;
    }
    }

    .item-group {
        padding: 20px 0 8px 24px;
        font-size: 0;
    a {
        color: rgba(0, 0, 0, 0.65);
        display: inline-block;
        font-size: 14px;
        margin-bottom: 13px;
        width: 25%;
    }
    }

    .members {
    a {
        display: block;
        margin: 12px 0;
        line-height: 24px;
        height: 24px;
    .member {
        font-size: 14px;
        color: rgba(0, 0, 0, .65);
        line-height: 24px;
        max-width: 100px;
        vertical-align: top;
        margin-left: 12px;
        transition: all 0.3s;
        display: inline-block;
    }
    &:hover {
    span {
        color: #1890ff;
    }
    }
    }
    }

    .mobile {

    .project-list {

    .project-card-grid {
        width: 100%;
    }
    }

    .more-info {
        border: 0;
        padding-top: 16px;
        margin: 16px 0 16px;
    }

    .headerContent .title .welcome-text {
        display: none;

      }
    }

    </style>

